package com.tensquare.friend.service;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.dao.FriendDao;
import com.tensquare.friend.dao.NoFriendDao;
import com.tensquare.friend.pojo.Friend;
import com.tensquare.friend.pojo.NoFriend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author:zimmor
 * @Date: 2021/3/15 19:33
 * @Description 交友业务逻辑层
 * @version: 1.0.0
 */
@Service
@Transactional
public class FriendService {
    @Autowired
    private FriendDao friendDao;

    @Autowired
    private NoFriendDao noFriendDao;

    @Autowired
    private UserClient userClient;

    public void addFriend(String userid, String friendid, String type) {

        //喜欢
        if("1".equals(type.trim())) {
            Friend friend = new Friend();
            if(friendDao.findFriendCount(userid, friendid)>0) {
                //他两有关系，单方面喜欢或是相互喜欢
                return;
            }
            friend.setFriendid(friendid);
            friend.setUserid(userid);
            friend.setIslike("0");
            friendDao.save(friend);
            userClient.attention(friendid);
            if(friendDao.findFriendCount(friendid, userid)>0) {
                friendDao.updateFriend(userid, friendid, "1");
                friendDao.updateFriend(friendid, userid, "1");
            }
        } else {
            //不喜欢
            NoFriend noFriend = new NoFriend();
            noFriend.setFriendid(friendid);
            noFriend.setUserid(userid);
            noFriendDao.save(noFriend);
        }
    }

    /**
     * 删除好友
     * @param userid
     * @param friendid
     */
    public void deleteFriendById(String userid, String friendid) {
        //从好友列表中删除好友
        friendDao.deleteFriend(userid, friendid);
        //如果是互关的好友，更新被删除好友的islike为0
        if(friendDao.findFriendCount(friendid, userid)>0) {
            friendDao.updateFriend(friendid, userid, "0");
        }
        //添加到非好友列表中
        noFriendDao.save(new NoFriend(userid, friendid));
        userClient.cancleAttention(friendid);
    }
}
